<?php

/**
 * This file is part of the Pagizer package.
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 *
 * @copyright   Copyright (c) 2010 Advisa (http://www.advisa.fr)
 * @author      Pagizer Core Team <team@pagizer.org>
 * @package     Pagizer
 * @subpackage  backoffice
 */

class m_backoffice_actions_block_modal_ModalClearCacheAction extends f_core_Action
{
	public function execute()
	{
        $formValues = $this->getFormValues('form');

        if(isset($formValues['submit']))
        {
            if(isset($formValues['html']))
            {
                f_template_Template::getInstance()->clear_all_cache();
            }

            if(isset($formValues['documents']))
            {
                $baseDir = WEBAPP_DIR.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR.'documents';
                if(is_dir($baseDir))
                {
                    $folders = glob($baseDir.DIRECTORY_SEPARATOR.'*', GLOB_ONLYDIR);
                    if(count($folders) > 0)
                    {
                       foreach($folders as $folder)
                       {
                            $this->delTree($folder);
                       }
                    }
                }
            }

            if(isset($formValues['urls']))
            {
                $baseDir = WEBAPP_DIR.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR.'url';
                if(is_dir($baseDir))
                {
                    $files = glob($baseDir.DIRECTORY_SEPARATOR.'*.cache');
                    if(count($files) > 0)
                    {
                       foreach($files as $file)
                       {
                            unlink($file);
                       }
                    }
                }
            }

            if(isset($formValues['routes']))
            {
                $baseDir = WEBAPP_DIR.DIRECTORY_SEPARATOR.'cache'.DIRECTORY_SEPARATOR.'routes';
                if(is_dir($baseDir))
                {
                    $folders = glob($baseDir.DIRECTORY_SEPARATOR.'*', GLOB_ONLYDIR);
                    if(count($folders) > 0)
                    {
                       foreach($folders as $folder)
                       {
                            $this->delTree($folder);
                       }
                    }
                }
            }

            $this->addToModel('status', 'success');
        }

		$this->setView('success');
	}	
	
	public function validate()
	{
		return true;
	}
	
    private function delTree($dir)
    {
        $files = glob( $dir . '*', GLOB_MARK );
        foreach( $files as $file )
        {
            if( substr( $file, -1 ) == '/' )
                $this->delTree( $file );
            else
                unlink( $file );
        }

        if (is_dir($dir)) rmdir( $dir );
    }
}